﻿using System.Collections;
using System.Data;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Text.Unicode;

namespace U8DllPack.Controller
{
    public static class JsonHelper
    {
        private static readonly JsonSerializerOptions JsonOption = new()
        {
            Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
            WriteIndented = true
        };

        /// <summary>
        /// 把json字符串转成对象
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="data">json字符串</param> 
        public static T? Deserialize<T>(string data)
        {
            return JsonSerializer.Deserialize<T>(data, JsonOption);
        }

        /// <summary>
        /// 把对象转成json字符串
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns>json字符串</returns>
        public static string Serialize(object o)
        {
            return JsonSerializer.Serialize(o);
        }

        /// <summary>
        /// 把DataTable对象转成json字符串
        /// </summary> 
        public static string ToJson(DataTable dt)
        {
            ArrayList arrayList = [];
            foreach (DataRow dataRow in dt.Rows)
            {
                Dictionary<string, object> dictionary = [];
                foreach (DataColumn dataColumn in dt.Columns)
                {
                    dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName]);
                }
                arrayList.Add(dictionary);
            }
            string json = JsonSerializer.Serialize(arrayList);
            return FixJsonDateTime(json);
        }
        /// <summary>
        /// 把DataRow对象转成json字符串
        /// </summary>
        /// <param name="dr">DataRow对象</param>
        /// <returns></returns>
        public static string ToJson(DataRow dr)
        {
            ArrayList arrayList = [];
            Dictionary<string, object> dictionary = [];
            foreach (DataColumn col in dr.Table.Columns)
            {
                dictionary.Add(col.ColumnName, dr[col.ColumnName]);
            }
            arrayList.Add(dictionary);
            string json = JsonSerializer.Serialize(arrayList);
            return FixJsonDateTime(json);
        }
        /// <summary>
        /// 将时间格式转换为适合阅读习惯的格式
        /// </summary>
        /// <param name="json">json字符串</param>
        /// <returns></returns>
        private static string FixJsonDateTime(string json)
        {
            json = Regex.Replace(json, @"\\/Date\((\d+)\)\\/", match =>
            {
                DateTime Datetime = new(1970, 1, 1);
                Datetime = Datetime.AddMilliseconds(long.Parse(match.Groups[1].Value));
                Datetime = Datetime.ToLocalTime(); //本地时间
                return Datetime.ToString("yyyy-MM-dd HH:mm:ss"); ;
            });
            return json;
        }

        /// <summary>
        /// 是否为Json
        /// </summary>
        /// <param name="json">json字符串</param>
        /// <returns></returns>
        public static bool IsJson(string json)
        {
            bool isjson = true;
            try
            {
                object? obj_json = Deserialize<object>(json);
            }
            catch (Exception ex)
            {
                isjson = false;
                BaseCls.WriteLog("判断是否Json，错误：" + ex.Message);
            }
            return isjson;
        }
        /// <summary>
        /// Unicode转为汉字
        /// </summary>
        /// <param name="unicode"></param>
        /// <returns></returns>
        public static string UnicodeToString(string unicode)
        {
            string result = string.Empty;
            //正则匹配
            Regex reg = new(@"(?i)\\u([0-9a-f]{4})");
            result = reg.Replace(unicode, delegate (Match m)
            {
                return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString();
            });
            return result;
        }
    }
}
